from fastapi import HTTPException, UploadFile
from app.config import settings
import os

def validate_file_type(file: UploadFile):
    """验证文件类型"""
    file_extension = os.path.splitext(file.filename)[1].lower()
    if file_extension not in settings.ALLOWED_FILE_TYPES:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的文件类型。请上传 {', '.join(settings.ALLOWED_FILE_TYPES)} 文件"
        )
    return file

def validate_file_size(file: UploadFile):
    """验证文件大小"""
    # 获取文件大小
    file.file.seek(0, 2)  # 移动到文件末尾
    file_size = file.file.tell()  # 获取文件大小
    file.file.seek(0)  # 重置文件指针到开头

    if file_size > settings.MAX_FILE_SIZE:
        raise HTTPException(
            status_code=400,
            detail=f"文件过大。最大允许 {settings.MAX_FILE_SIZE // (1024*1024)}MB"
        )
    return file